<?php
class messagesActions extends baseDisplayActions{
  
  function getClassName($request){  	
  	return 'message';
  }
  
   public function executeRenderList(sfWebRequest $request)
  {
  	$user = sfContext::getInstance()->getUser()->getUserProfile();
	$this->hide = array();
	$this->add = array();	
    $className = $this->getClassName($request);
    
  	$this->orderByCol = $request->getParameter('order');
  	$page = (int)$request->getParameter('page',1);
    $this->view = $request->getParameter('view', 'mesmessages');
    if(empty($this->view)) $this->view = 'mesmessages';
	$this->objDef = new objectDef($className);
	$descCol = $this->objDef->descriptor;
	if(empty($this->orderByCol)){
  		if($descCol!=''){
  			$this->orderByCol =  $this->objDef->orderFields;
  			if($this->orderByCol=='') {
  				$this->orderByCol = $descCol.'*asc';	
  			}
  		}
  	}

  	$orderSens = 'asc';
	$orderArray = array();
    if(!empty($this->orderByCol)){
    	$arrayTmp = explode(';',$this->orderByCol);
    	foreach($arrayTmp as $orderString){
    		$orderColArray=explode('*',$orderString);
    		if(count($orderColArray)>0){
    			if(isset($orderColArray[1]))
    				$orderSens = $orderColArray[1];
    		}
    		$orderArray[] = $orderColArray;
    	}
    	
    }else{
    	$orderColArray=array();
    }
  	$orderArray[] = array('id',$orderSens);  	
  	$this->q = $this->objDef->getBaseQuery($this->hide, $this->add, $orderArray);
    if($this->view=='destinedtome'){
    	$this->objDef->isReadOnly = true;
    	$this->objDef->canBeDeleted = false;
    	$this->q->innerJoin('a.notification n WITH n.evenementclass = ? ', 'message')
    	  ->addWhere('n.personne_id = ?', $user->id);
    	$this->hide = array('public', 'datefin' , 'datedebut', 'etat');    	
	}elseif($this->view=='all'){
		$this->objDef->isReadOnly = true;
		$this->objDef->canBeDeleted = false;
	}else{
  		$this->q->addWhere('a.created_by_id = ?', $user->id);
	}
  	$search = new searchBar();	
	$search->addFilterstoQuery($this->q);
	$this->q->setHydrationMode(Doctrine_Core::HYDRATE_ARRAY);
    $this->nbPosts = $request->getParameter('nbPosts');
	if(!isset($this->nbPosts) or $this->nbPosts == 0){
		$this->nbPosts = sfConfig::get('app_posts_number_per_page', 10);
	}
	$this->pager = $search->setPager($request, $this->q, $this->nbPosts, $page);
	$this->totalRecords = $this->pager->getNbResults();
		
	$this->records = $this->pager->getResults(); //$q->execute();
	
	$this->addButton = !$this->objDef->isReadOnly;
	$this->orderParams = '1'; /*So it will go back to first page when users click to order by*/
	$this->module = $this->getModuleName();
	$this->moduleRef = 'messages';
	
  	return $this->renderPartial('list'); 
	
  }
  
  public function executeIndex(sfWebRequest $request){
  	$this->view = $request->getParameter('view');
  	parent::executeIndex($request);
  	if($this->getUser()->getAttribute('current_app')=='touch'){
		$this->setLayout('layoutTouch');
		$response = $this->getResponse();
  		$response->addStyleSheet('default/touchScreen.css');
  		$response->removeStyleSheet('default/layout_setup.css?v'.sfConfig::get('app_version_numero'));
	}; 
  	
  }
  
  public function executeShow(sfWebRequest $request){
  	parent::executeShow($request);
  	if($this->self->public){
  		$this->hide = array('roles', 'destinataires');
  	}else{
  		$this->hide = array('datedebut', 'datefin');
  	}
  	if($this->getUser()->getAttribute('current_app')=='touch'){
		$this->setLayout('layoutTouch');
		$response = $this->getResponse();
  		$response->addStyleSheet('default/touchScreen.css');
  		$response->removeStyleSheet('default/layout_setup.css?v'.sfConfig::get('app_version_numero'));
	}; 
  }
  
 
  public function preExecute(){
  	/*Get all this parameters in order to go back to the same view I was.*/
  	$request = $this->getContext()->getRequest();
 	$this->view = $request->getParameter('view');
	$this->objDef = new objectDef('message');
	$this->actualPage = $request->getParameter('page',1);
	$this->order = $request->getParameter('order', 'id*desc');
	$this->orderByCol= $request->getParameter('order', 'id*desc');
  	
  }
  
  function executeSendMessage(sfWebRequest $request){
  	$this->message = Doctrine::getTable('message')->find($request->getParameter('message_id'));
  	$confirm = $request->getParameter('confirm');
  	if($this->message){
  		if($this->message->etat == '1'){
  			$personne_id = $request->getParameter('personne_id', 0);
  			if($personne_id){
  				$personne = Doctrine::getTable('personne')->find($personne_id);
  			}else{
  				$personne = false;
  			}
			
			$result = ambnoyFuncs::createNotifications($this->message, false, $personne);
			
		}else{
			$result =array('result'=>'Le message déjà confirmé');
		}
  	}else{
  		$result =array('result'=>'Message non trouvé');
	}
  	if($confirm==1){
		$this->message->etat= 3; //Etat = non lu
	 	$this->message->save();
	 	//ambnoyFuncs::sendToBigBrother($this->message, 'message');
 	}
  	return $this->renderText(json_encode($result));
  }
  
  function executeGetDestinataires(sfWebRequest $request){
  	$this->message = Doctrine::getTable('message')->find($request->getParameter('id'));
  	$personnes = array();
  	if($this->message){
  		$personnes = $this->message->getArrayDestinataires();
  	}
  	return $this->renderText(json_encode($personnes)); 
  	
  }

  public function executeCreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod('post'));

    
  	$formClass = $this->getClassName($request).'Form';
    $this->form = new $formClass();
   	$this->owner_id = $request->getParameter('owner_id', null);
    if(!is_null($this->owner_id))
    {

    	$owner_field = $this->form->getOwnerField('List');
    	$this->form->setDefault($owner_field, $this->owner_id);
    	$this->form->hideWidget(substr($owner_field, 0, strlen($owner_field)-3)); //hide widget. Use of substr to take out _id
    }    
	$this->className = $this->getClassName($request);
	$this->module = $this->getModuleName();
    
    $this->self = $this->processForm($request, $this->form, false);

    if($this->self){
    	$this->redirect('messages/index?view=' . $this->view .'&order='.$this->orderByCol.'&page='.$this->actualPage);
    }
	$this->objDef = new objectDef($this->className);
	$this->itemsForms = array();
  	if($this->objDef->hasAttach){
		$this->formAttach = new attachmentForm();
	}
    $this->setTemplate('new');
  }
  
  public function executeDelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();

    $this->forward404Unless($self = Doctrine::getTable($this->getClassName($request))->find($request->getParameter('id')), sprintf('Object sf_producto does not exist (%s).', $request->getParameter('id')));
	$this->owner_id = $request->getParameter('owner_id', null);
	if(!is_null($this->owner_id))
	{
		$ownerData = Util::getOwnerFieldAndClass($self, 'List');  
		$this->owner_field = $ownerData['ownerField'];
		$this->ownerClass = $ownerData['ownerClass'];
	}	    
    $self->delete();
    $this->redirect('messages/index?view=' . $this->view .'&order='.$this->orderByCol.'&page='.$this->actualPage);
   
    
  }
  
  public function executeUpdate(sfWebRequest $request)
  {
  	$className = $this->getClassName($request);
    $this->forward404Unless($request->isMethod('post') || $request->isMethod('put'));
    $this->forward404Unless($self = Doctrine::getTable($className)->find($request->getParameter('id')), sprintf('Object does not exist (%s).', $request->getParameter('id')));

    $formClass = $className.'Form';
    $this->form = new $formClass($self);
    $this->self = $this->processForm($request, $this->form, false);
	
    if($this->self){
    	$this->redirect('messages/index?view=' . $this->view .'&order='.$this->orderByCol.'&page='.$this->actualPage);
    }

    $this->owner_id = $request->getParameter('owner_id', null);
    if(!is_null($this->owner_id))
    {
    	$owner_field = $this->form->getOwnerField('List');
    	$this->form->hideWidget(substr($owner_field, 0, strlen($owner_field)-3)); //hide widget. Use of substr to take out _id
    }    
    $this->itemsForms = array();
	$this->className = $className;
	$this->module = $this->getModuleName();
    
  	$this->objDef = new objectDef($this->className);

	if($this->objDef->hasAttach){
  		$q = Doctrine::getTable('attachment')
			->createQuery('m')
			->where('owner_id= ?',$self->id)
			->andWhere("ownerclass = ?",get_class($self));
		$records =	$q->execute();
  		$files = array();
  		foreach($records as $attachment){
  			$files[$attachment['file']] = $attachment;
  		}
		$this->formAttach = new attachmentForm();
		$this->getUser()->setAttribute('filesToUpload', $files);
	}
	
	$this->setTemplate('edit');
    
  }
  
  
  public function executeConfirmMessage(sfWebRequest $request){
    $this->orderByCol = $request->getParameter('order');
  	$page = (int)$request->getParameter('page',1);
    $this->view = $request->getParameter('view');
    
  	$formClass = $this->getClassName($request).'Form';
    $this->self = Doctrine::getTable('message')->find($request->getParameter('id'));
  	
  	$this->className = $this->getClassName($request);
	$this->module = $this->getModuleName();
  	$this->objDef = new objectDef($this->className);
  	if($this->self){
	    if($this->self->public){
	    	$this->self->etat = 2;
	    	//ambnoyFuncs::sendToBigBrother($this->self, 'message');
	    }else{
	    	$this->self->etat = 3; //Non Lu
	    }
	    $this->self->save();
  	}	
    $this->redirect('messages/index?view=' . $this->view .'&order='.$this->orderByCol.'&page='.$page);
  }

  public function executeSaveAndSend(sfWebRequest $request){
 	$this->forward404Unless($request->isMethod('post') || $request->isMethod('put'));
    
  	$formClass = $this->getClassName($request).'Form';
    $self = Doctrine::getTable('message')->find($request->getParameter('id'));
  	if($self){
  		$this->form = new $formClass($self);
    }else{
    	$this->form = new $formClass();
    }
  	$this->self = $this->processForm($request, $this->form, false);
	$this->className = $this->getClassName($request);
	$this->module = $this->getModuleName();
  	$this->objDef = new objectDef($this->className);
  	if($this->self){
	    $this->setTemplate('show');
	    if($this->self->public){
	    	$this->self->etat = 2; //Publié
	    	$this->self->save();
	    	$this->sendMessages = false;
	    	//ambnoyFuncs::sendToBigBrother($this->self, 'message');
	    }else{
	    	$this->sendMessages = true;	
	    }
		
    }else{
    	$this->itemsForms = array();
		if($this->objDef->hasAttach){
	  		$q = Doctrine::getTable('attachment')
				->createQuery('m')
				->where('owner_id= ?',$self->id)
				->andWhere("ownerclass = ?",get_class($this->form->getObject()));
			$records =	$q->execute();
	  		$files = array();
	  		foreach($records as $attachment){
	  			$files[$attachment['file']] = $attachment;
	  		}
			$this->formAttach = new attachmentForm();
			$this->getUser()->setAttribute('filesToUpload', $files);
		}		
    	$this->setTemplate('edit');
    }
	 
  }
  
}